import React, { useState, useEffect } from "react"
import marked from 'marked';
import service from "@@/services/user.service"
import { BaseEventOrig, Image, Picker, Text, View, Video, RichText } from "@tarojs/components"
import {
    useDidHide,
    useDidShow,
    usePageScroll,
    usePullDownRefresh,
    useReachBottom,
    useReady,
    useResize,
    useTabItemTap,
    navigateTo,
    downloadFile,
    openDocument,
    saveFile,
    Current,
} from "@tarojs/taro"
import NavLayout from "@@/components/layout/nav.layout"
import TBread from "@@/t-ui/bread.tui"
import TTabs from "@@/t-ui/tabs.tui"

import { Swiper, SwiperItem } from '@tarojs/components'
import { recommendProductResType } from "@@/interfaces/api.interface"
import ProxyConfig from "@@/../config/proxy"
import "./recommendDetail.scss"

type breadType = {
    name: string | undefined
}
const Index = () => {
    const [current, setCurrent] = useState<number>(0)//当前滑块的index
    const [currentTab, setCurrentTab] = useState<number>(0)//当前tab值
    const [open, setOpen] = useState(false) //打开弹窗
    const [swiperList, setSwiperList] = useState<string[]>([])
    const [breadList, setBreadList] = useState<breadType[]>([])

    const [product, setProduct] = useState<recommendProductResType>()//
    const [videoUrl, setVideoUrl] = useState<string>()
    useEffect(() => {
        setBreadList([
            { name: "SMB" },
            { name: decodeURI(Current.router?.params?.oneMenu || "") },
            { name: "产品详情" },
        ])

        let id = Number(Current.router?.params?.id)
        service.recommendProduct({ id }).then(res => {
            if (res.code === 200) {
                setProduct(res.data)
                let list: string[] = res.data.detailMaps && res.data.detailMaps.map(item => item.url) || []
                // console.log([res.data.image, ...list])
                setSwiperList([res.data.image, ...list])
                if (res.data.videos) {
                    setVideoUrl(res.data.videos[0].url || "")
                }
            }
        })
    }, [])

    //下载文档
    const downloadDoc = (url: string) => {
        if (TARO_ENV === "h5") {
            window.open(`${ProxyConfig.sourceUrl}/${url}`)
        }
        if (TARO_ENV === "weapp") {
            downloadFile({
                url: `${ProxyConfig.sourceUrl}/${url}`,//'https://example.com/audio/123', //仅为示例，并非真实的资源
                filePath: "",
                success: function (res) {
                    // 只要服务器有响应数据，就会把响应内容写入文件并进入 success 回调，业务需要自行判断是否下载到了想要的内容
                    if (res.statusCode === 200) {
                        // console.log(res)
                        // saveFile({
                        //     tempFilePath: res.tempFilePath,
                        //     success: function (res) {
                        //         console.log(res)
                        //     }
                        // })
                        openDocument({
                            filePath: res.tempFilePath,
                            success: function (res) {
                                console.log(res)
                            }
                        })
                    }
                }
            })
        }

    }
    // swiper
    const onChange = (e: any) => {
        // if (swiperList instanceof Array) {
        //     if (e.detail.current < swiperList && swiperList?.length) {

        //     }
        // }
        setCurrent(e.detail.current)
    }

    //点击视频列表 播放视频
    const playVideo = (url: string) => {
        setVideoUrl(url)
        setOpen(true)
    }
    const closePop = () => {
        setOpen(false)
    }
    const tabList = [{ title: '产品概述' }, { title: '技术参数' }, { title: '尺寸图' }, { title: '订货型号' }, { title: '产品视频' }, { title: '文档下载' }];
    const paneList = [
        {
            content: product && <View className={"tab_box summary_box"}><RichText nodes={marked(product?.content).replace(/<img/g, "<img class='markimg'")}></RichText></View>//<View className={"tab_box summary_box"} dangerouslySetInnerHTML={{ __html: product?.content }}></View>
        },
        {
            content: product && <View className={"tab_box parameter_box"} dangerouslySetInnerHTML={{ __html: product?.parameter }}></View>
        },
        {
            content: product && <View className={"tab_box size_box"}>
                {
                    product.dimensionalDrawing && product.dimensionalDrawing[0] && product.dimensionalDrawing.map(item => {
                        return <View className='img_box' key={item.url}>
                            <Image mode="widthFix" src={`${ProxyConfig.sourceUrl}/${item?.url}`} />
                        </View>
                    })
                }
            </View>
        },
        {
            content: product && <View className={"tab_box model_box"}>{product.model}</View>
        },
        {
            content: product && <View className={"tab_box video_list_box"}>
                {
                    product.videos && product.videos[0] && product.videos.map(item => {
                        return <View className='img_box' onClick={playVideo.bind(this, item.url)} key={item.videoImg}>
                            <Image src={`${ProxyConfig.sourceUrl}/${item?.videoImg}`} />
                        </View>
                    })
                }
            </View>
        },
        {
            content: product && <View className={"tab_box download_box"}>
                {
                    product.documents && product.documents[0] && product.documents.map(item => {
                        return <View className={"item_box"} key={item.url}>
                            <View className={'img_box'}><Image mode={"aspectFit"} src={require('@@/assets/img/product/doc.png')} /></View>
                            <Text onClick={downloadDoc.bind(this, item.url)}>推荐产品</Text>
                            <View className={'img_box img_box2'}><Image mode={"aspectFit"} src={require('@@/assets/img/product/download.png')} /></View>
                        </View>
                    })
                }
            </View>
        }
    ]
    return (
        <NavLayout border leftIconType="chevron-left" color="#141414" id="recommendDetailPage">
            <TBread breadList={breadList} />
            {
                swiperList.length && <View className={'swiper_box'}>
                    <Swiper
                        indicatorColor='#999'
                        indicatorActiveColor='#333'
                        current={current}
                        circular
                        onChange={onChange}
                    // autoplay
                    >
                        {
                            swiperList.map((item, index) => {
                                return <SwiperItem key={index}>
                                    <View className={'img_box'}>
                                        <Image mode="widthFix" src={`${ProxyConfig.sourceUrl}/${item}`} />
                                    </View>
                                </SwiperItem>
                            })
                        }
                    </Swiper>
                    <View className={"level"}>{`${current + 1}/${swiperList?.length}`}</View>
                </View>
            }
            <View className={"head"}>
                <View className={"title"}>{product?.title}</View>
                <View className={"text"}>280KG单门防水磁力锁</View>
            </View>
            <TTabs swipeable scroll current={currentTab} tabList={tabList} paneList={paneList} onClick={(val) => {
                setCurrentTab(val)
            }} />
            <View className={"copyright_box"}>
                <View className={"copyright"}>
                    <View>版权所有 © 浙江大华技术股份有限公司 1998-2021。 </View>
                    <View>保留一切权利。备案号A4-254545477号</View>
                </View>
            </View>

            {/* 弹窗 */}
            <View className={'pop'} style={{ display: open ? "block" : "none" }}>
                <View className={"close_layer"} onClick={closePop}></View>
                {
                    product && <View className='video_box'>
                        {/* 'https://www.w3school.com.cn/i/movie.mp4' */}
                        <Video
                            src={`${ProxyConfig.sourceUrl}/${videoUrl}`}
                            controls={true}
                            autoplay={false}
                            enablePlayGesture={true}
                            poster='https://misc.aotu.io/booxood/mobile-video/cover_900x500.jpg'
                            initialTime={0}
                            id='video'
                        />
                    </View>
                }
            </View>
        </NavLayout>
    )
}

export default Index